package com.sxf.test;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class JDBC {
	static {
		// String driverClassName = "oracle.jdbc.driver.OracleDriver";
		String driverClassName = "com.mysql.jdbc.Driver";

		try {
			Class.forName(driverClassName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		// String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
		// String username = "scott";
		// String pwd = "tiger";

		String url = "jdbc:mysql://127.0.0.1:3306/test?&amp;useUnicode=true&amp;characterEncoding=UTF-8";
		String username = "root";
		String pwd = "123456";

		Connection con = null;
		try {
			con = DriverManager.getConnection(url, username, pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	@Test
	public void test() {
		Connection con = getConnection();
		try {
			DatabaseMetaData dbmd = con.getMetaData();
			ResultSet rs = dbmd.getTableTypes();
			List<String> typeList = new ArrayList<String>();
			while (rs.next()) {
				typeList.add(rs.getString(1));
			}

			String[] type = new String[typeList.size()];
			for (int i = 0; i < typeList.size(); i++) {
				type[i] = typeList.get(i);
				System.out.print(typeList.get(i) + " ");
			}
			System.out.println();

			rs = dbmd.getTables(null, dbmd.getUserName(), null, type);
			ResultSetMetaData rsmd = rs.getMetaData();

			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
				System.out.print(rsmd.getColumnName(i) + " ");
			}
			System.out.println();

			while (rs.next()) {
				for (int i = 1; i <= rsmd.getColumnCount(); i++) {
					System.out.print(rs.getString(i) + " ");
				}
				System.out.println();
			}

		} catch (SQLException e) {

			e.printStackTrace();
		}
	}
}
